package cn.swu.ws.webCounter;
import jakarta.servlet.ServletContext;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
@WebListener
public class WebCounter implements HttpSessionListener {
    public static  int counter = 1;
    /**
     * 监听session创建
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer num = (Integer) context.getAttribute("online_num");
        if(num == null)
            num = 0;
        ++num;
        counter = num;
        context.setAttribute("online_num",num);
        System.out.println("新增一位用户...");
    }
    /**
     * 监听session销毁
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer num = (Integer) context.getAttribute("online_num");
        if(num == null)
            num = 0;
        else
            --num;
        context.setAttribute("online_num",num);
        counter = num;
        System.out.println("减少一位用户...");
    }
}


